package org.vergil.utils.secure;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * sha 256 加密方法类
 * @author: vergil
 * @Date: 2018/4/22
 * @since 1.0.0
 */
public class SHA256 {
    private static final String ALGORITHM = "SHA-256";
    private MessageDigest messageDigest;
    private int count = 1;
    private String key;

    SHA256() {
        try {
            this.messageDigest = MessageDigest.getInstance(ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
            return;
        }
    }

    /**
     * 加密迭代次数
     *
     * @auther: vergil
     * @date: 2018/5/13
     */
    public SHA256 count(int count) {
        if (count > 0) {
            this.count = count;
        }
        return this;
    }

    /**
     * 设置key
     *
     * @auther: vergil
     * @date: 2018/5/13
     */
    public SHA256 key(String key) {
        if (null != key || !key.isEmpty()) {
            this.key = key;
        }
        return this;
    }

    public byte[] encrypt(byte[] content) {
        byte[] encryptByte = content;
        if (null != key && !key.isEmpty()) {
            encryptByte = (new String(content) + key).getBytes();
        }
        for (int i = 1; i <= count; i++) {
            encryptByte = messageDigest.digest(encryptByte);
        }
        return Base64.getEncoder().encode(encryptByte);
    }

    public String encrypt(String content) {
        byte[] encryptByte;
        if (null != key && !key.isEmpty()) {
            content = content + key;
        }
        encryptByte = content.getBytes();
        for (int i = 1; i <= count; i++) {
            encryptByte = messageDigest.digest(encryptByte);
        }
        return Base64.getEncoder().encodeToString(encryptByte);
    }
}
